package com.cyc.pool;

import java.util.concurrent.*;

public class Demo2 {
    public static void main(String[] args) {

        //CPU 核数
        int i1 = Runtime.getRuntime().availableProcessors();
        /**
         * 自定义线程池
         */
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                i1,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了 尝试与第一个竞争
//                new ThreadPoolExecutor.DiscardPolicy() //队列满了，不会抛出异常
//                new ThreadPoolExecutor.CallerRunsPolicy() //哪来的回哪去
//                new ThreadPoolExecutor.AbortPolicy() //银行满了，还有人进来，不处理并抛出异常
        );
        try {
            //最大承载 Deque+max = 8
            // 当大于8时
            // 升级 new ThreadPoolExecutor.DiscardOldestPolicy() 策略时 会尝试去与最早的线程去竞争 赢了获取线程 竞争失败 则丢掉任务 不抛出异常
            // new ThreadPoolExecutor.AbortPolicy() 策略时 java.util.concurrent.RejectedExecutionException
            // new ThreadPoolExecutor.CallerRunsPolicy() 策略时 有main线程执行
            // new ThreadPoolExecutor.DiscardPolicy() 策略时 不抛出异常，丢掉任务
            for (int i = 0; i < 9; i++) {
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" "+" OK");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}
